package com.ny.controller;
import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.until.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    Map<String,Object> map = new HashMap<>();
    @RequestMapping("/selectUser")
    public Result selectUser(){
        return Result.success(userService.findAll());
    }
    @PostMapping("/findUser")
    public Result findUser(String username,String password){
        User user = userService.findUser(username,password);
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUsername());
            jwtUtil.storeToken(token, user.getUsername());
            map.put("token", token);
            map.put("users", user);
            return Result.success(map);
        } else {
            return Result.error ("用户名和密码错误");//
        }
    }

    // 注册
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (userService.register(user)) {
            return Result.success("注册成功");
        } else {
            return Result.error("用户已存在");
        }
    }
    @GetMapping("/findNickname")
    public Result findNickname(@RequestParam String nickname) {
        return Result.success(userService.findNickname(nickname));
    }


    //    查询邮箱号是否存在:http://localhost:8081/findUserByEmail?email=<EMAIL>
    @PostMapping("/findUserByEmail")
    public Result findUserByEmail(String email){
        if(userService.findUserByEmail(email)>0){
            return Result.success("邮箱号已存在");
        }
        return Result.success("邮箱号不存在");
    }
    //    给邮箱发送验证码：http://localhost:8081/sendEmail?email=<EMAIL>
    @PostMapping("/sendEmail")
    public Result sendEmail(String email){
        if(userService.findUserByEmail(email)<=0){
            return Result.error("邮箱号不存在");
        }
        userService.sendEmail(email);
        return Result.success("发送成功");
    }
    //  http://localhost:8081/updateUser?email=<EMAIL>&code=123456&newPassword=123456
    @PostMapping("/updateUser")
    public Result updateUser(@RequestParam String email,@RequestParam String code, @RequestParam String newPassword){
        //判断验证码是否正确
        if(userService.findEmail(email,code)){
//         进行修改密码
            if (userService.updateUser(email,newPassword)>0){
                return Result.success("修改成功");
            }
            return Result.error("修改失败");
        }
        else {
            return Result.error("验证码不正确");
        }
    }
}
